package com.inno.game.handler;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.inno.game.bean.User;
import com.inno.game.service.UserService;
import com.inno.game.util.JSONHelper;
import com.inno.game.util.Result;

@Scope("prototype")
@Controller("SocketHandler")
public class SocketHandler implements Runnable{
	private Socket client;
	private User user = new User();

	@Resource(name="UserService")
	private UserService userService;
	public SocketHandler()
	{}
	public SocketHandler(Socket socket)
	{
		this.client = socket;
	}
	
	@Override
	public void run() {
		DataOutputStream dos = null;
		try {
			client.setSoTimeout(1);
			dos = new DataOutputStream(client.getOutputStream());
			dos.writeUTF("1");
			dos.flush();
		} catch (IOException e1) {
			try {
				dos.writeUTF("-1");
				dos.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}
		while (true) {
			if (client.isClosed()) {
				break;
			}
			try {
				BufferedInputStream bis = new BufferedInputStream(client.getInputStream());
				BufferedReader bReader = new BufferedReader(new InputStreamReader(bis));
				String str = bReader.readLine();
				StringBuffer sb = new StringBuffer();
				while (str != null) {
					if (str.isEmpty()) {
						break;
					}
					sb.append(str);
					str = bReader.readLine();
				}
				if (sb.toString().isEmpty()) {
					continue;
				}
				String re = handle(sb.toString()).toString();
				dos.writeUTF(re);
				dos.flush();
			} catch (IOException e) {
			} catch (Exception e) {
			}
		}

		try {
			client.close();
			System.out.println("用户: " + user.getN() + "退出!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public Result handle(String str)
	{
		System.out.println("rec: "+str);
		String method = str.substring(0, str.indexOf(":"));
		String jsonStr = str.substring(str.indexOf(":")+1);
		user = (User) JSONHelper.parserBean(jsonStr);
		int m = Integer.parseInt(method);
		switch (m) {
		case 1://log in
			return userService.login(user);
		case 2://register
			return userService.register(user);
		default:
			break;
		}
		return Result.Connection_Success;
	}
	
	public Socket getClient() {
		return client;
	}
	public void setClient(Socket client) {
		this.client = client;
	}
}